package com.waverider.promotion.web.bg.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.waverider.promotion.biz.manager.ItemManager;
import com.waverider.promotion.web.AbstractLoginedController;

public class PublishPromotionAction extends AbstractLoginedController {
	ItemManager itemManager;

	public final void setItemManager(ItemManager itemManager) {
		this.itemManager = itemManager;
	}

	@Override	
	protected ModelAndView handleLogined(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String checkFlag = request.getParameter("checkFlag");
		if ("checkOne".equals(checkFlag))
			checkOne(request, response);
		if ("checkSomeOrAll".equals(checkFlag))
			checkSomeOrAll(request, response);
		return new ModelAndView("redirect:/bg/itemDisplayList.htm");
	}

	private void checkOne(HttpServletRequest request,
			HttpServletResponse response) {
		Long id = Long.valueOf(request.getParameter("goods_id"));
		Long promotionId = Long.valueOf(request.getParameter("promotionId"));

		itemManager.recommendOne(getSessionKey(request.getSession()), id,
				promotionId);
	}

	private void checkSomeOrAll(HttpServletRequest request,
			HttpServletResponse response) {
		String checkAll = request.getParameter("checkAll");
		Long promotionId = Long.valueOf(request.getParameter("promotionId"));
		if(promotionId.intValue() == -1)
			return;
		if ("checkAll".equals(checkAll)) {
			itemManager.recommendAll(getSessionKey(request.getSession()),
					promotionId, getShopId(request.getSession()));
		}
		if ("checkSome".equals(checkAll)) {
			List<Long> itemIdList = new ArrayList<Long>();
			String[] idString = request.getParameterValues("goods_id");
			for (int i = 0; i < idString.length; i++)
				itemIdList.add(Long.valueOf(idString[i]));

			itemManager.recommendSome(getSessionKey(request.getSession()),
					itemIdList, promotionId,getShopId(request.getSession()));
		}
		return;
	}

}
